package com.example.s7;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ReadExample {

    public static void main(String[] args) throws UaException, ExecutionException, InterruptedException {
        OpcUaClient client = new ClientExample().createClient();
        UaClient uaClient = client.connect().get();

        NodeId nodeId1 = new NodeId(4, "W201_momentary|dd");
        //NodeId nodeId1 = new NodeId(4, "V312A_liquid_in|t");

        NodeId nodeId2 = new NodeId(4, "DB4.V312A_liquid_in|t");
        NodeId nodeId3 = new NodeId(4, "NewConnection_2.DB4.V312A_liquid_in|t");
        NodeId nodeId4 = new NodeId(4, "TCP/IP.NewConnection_2.DB4.V312A_liquid_in|t");
        List<NodeId> nodeIds = new ArrayList<NodeId>() {{
            this.add(nodeId1);
            this.add(nodeId2);
            this.add(nodeId3);
            this.add(nodeId4);
        }};

        while (true) {
            final CompletableFuture<List<DataValue>> exceptionally = uaClient.readValues(
                    0d,
                    TimestampsToReturn.Neither,
                    nodeIds
            ).exceptionally(e -> {
                System.out.println(e);
                return null;
            });
            List<DataValue> dataValues = exceptionally.get();
            if (dataValues == null) {
                continue;
            }for (DataValue dataValue : dataValues) {
                System.out.println(dataValue.getValue().getValue());

//                System.out.println("[ns=" + nodeId.getNamespaceIndex() + ", id=" + nodeId.getIdentifier() + "] value is "
//                        + dataValue.getValue().getValue());
            }

            Thread.sleep(5000);
        }

//        uaClient.disconnect().get();
    }

}
